package com.ruoyi.paper.controller;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.paper.domain.ExamOption;
import com.ruoyi.paper.service.*;
import com.ruoyi.system.domain.SysStudent;
import com.ruoyi.system.service.ISysStudentService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.paper.domain.ExamPaper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.paper.domain.ExamFolder;
import com.ruoyi.paper.domain.ExamPaperLib;
import com.ruoyi.paper.domain.StudentScore;
import com.ruoyi.paper.domain.ExamPaperOption;
import org.apache.shiro.SecurityUtils;

/**
 * 实训试卷Controller
 * 
 * @author ruoyi
 * @date 2025-04-14
 */
@Controller
@RequestMapping("/jxsx/paper")
public class ExamPaperController extends BaseController
{
    private String prefix = "jxsx/paper";

    @Autowired
    private IExamPaperService examPaperService;
    @Autowired
    private IExamFolderService examFolderService;
    @Autowired
    private IExamOptionService examOptionService;
    @Autowired
    private IExamLibService examLibService;
    @Autowired
    private IExamPaperLibService examPaperLibService;
    @Autowired
    private ISysStudentService studentService;

    @RequiresPermissions("jxsx:paper:view")
    @GetMapping()
    public String paper(ModelMap mmap)
    {
        SysUser user = ShiroUtils.getSysUser();
        mmap.put("userRole", user.getRoles().get(0).getRoleKey().toString());
        return prefix + "/paper";
    }

    /**
     * 查询实训试卷列表
     */
    @RequiresPermissions("jxsx:paper:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ExamPaper examPaper)
    {
        startPage();

        List<ExamPaper> list = examPaperService.selectExamPaperList(examPaper);
        return getDataTable(list);
    }

    /**
     * 导出实训试卷列表
     */
    @RequiresPermissions("jxsx:paper:export")
    @Log(title = "实训试卷", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ExamPaper examPaper)
    {
        List<ExamPaper> list = examPaperService.selectExamPaperList(examPaper);
        ExcelUtil<ExamPaper> util = new ExcelUtil<ExamPaper>(ExamPaper.class);
        return util.exportExcel(list, "实训试卷数据");
    }

    /**
     * 新增实训试卷
     */
    @RequiresPermissions("jxsx:paper:add")
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存实训试卷
     */
    @RequiresPermissions("jxsx:paper:add")
    @Log(title = "实训试卷", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ExamPaper examPaper)
    {
        return toAjax(examPaperService.insertExamPaper(examPaper));
    }

    /**
     * 修改实训试卷
     */
    @RequiresPermissions("jxsx:paper:edit")
    @GetMapping("/edit/{paperId}")
    public String edit(@PathVariable("paperId") String paperId, ModelMap mmap)
    {
        ExamPaper examPaper = examPaperService.selectExamPaperByPaperId(paperId);
        mmap.put("examPaper", examPaper);
        return prefix + "/edit";
    }

    /**
     * 修改保存实训试卷
     */
    @RequiresPermissions("jxsx:paper:edit")
    @Log(title = "实训试卷", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ExamPaper examPaper)
    {
        return toAjax(examPaperService.updateExamPaper(examPaper));
    }

    /**
     * 删除实训试卷
     */
    @RequiresPermissions("jxsx:paper:remove")
    @Log(title = "实训试卷", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        String[] fruitArray = ids.split(",");
        return toAjax(examPaperService.deleteExamPaperByPaperIds(fruitArray));
    }

    /**
     * 智能组卷页面
     */
    @RequiresPermissions("jxsx:paper:edit")
    @GetMapping("/smartPaper/{paperId}")
    public String smartPaper(@PathVariable("paperId") String paperId, ModelMap mmap)
    {
        ExamPaper examPaper = examPaperService.selectExamPaperByPaperId(paperId);
        mmap.put("examPaper", examPaper);
        return prefix + "/smart_paper";
    }

    /**
     * 智能组卷保存
     */
    @RequiresPermissions("jxsx:paper:edit")
    @Log(title = "智能组卷", businessType = BusinessType.UPDATE)
    @PostMapping("/smartPaper")
    @ResponseBody
    public AjaxResult smartPaperSave(ExamFolder examFolder)
    {
        return toAjax(examPaperService.smartPaper(examFolder));
    }

    /**
     * 预览试卷
     */
    @RequiresPermissions("jxsx:paper:view")
    @GetMapping("/preview/{paperId}")
    public String preview(@PathVariable("paperId") String paperId, ModelMap mmap)
    {
        ExamPaper examPaper = examPaperService.selectExamPaperByPaperId(paperId);
        mmap.put("examPaper", examPaper);

        ExamFolder examFolder1=new ExamFolder();
        examFolder1.setPaperId(paperId);
        // 获取试卷规则
        List<ExamFolder> examFolders = examFolderService.selectExamFolderList(examFolder1);
        ExamFolder examFolder = examFolders.get(0);
        mmap.put("radioScore", examFolder.getRadioOneScore());
        mmap.put("checkboxScore", examFolder.getCheckboxOneScore());
        mmap.put("indefiniteScore", examFolder.getIndefiniteOneScore());
        mmap.put("subjectiveScore", examFolder.getSubjectiveOneScore());
        ExamPaperLib examPaperLib=new ExamPaperLib();
        examPaperLib.setPaperId(paperId);
        examPaperLib.setQuestionType("0");
        // 获取各类题型试题及其选项
        List<ExamPaperLib> radioQuestions = examPaperLibService.selectExamPaperLibList(examPaperLib);
        examPaperLib.setQuestionType("1");
        List<ExamPaperLib> checkboxQuestions = examPaperLibService.selectExamPaperLibList(examPaperLib);
        examPaperLib.setQuestionType("2");
        List<ExamPaperLib> indefiniteQuestions = examPaperLibService.selectExamPaperLibList(examPaperLib);
        examPaperLib.setQuestionType("3");
        List<ExamPaperLib> subjectiveQuestions = examPaperLibService.selectExamPaperLibList(examPaperLib);

        // 获取每道题的选项
        for (ExamPaperLib question : radioQuestions) {
            ExamOption option=new ExamOption();
            option.setLibId(question.getLibId());
            List<ExamOption> options = examOptionService.selectExamOptionList(option);
            question.setOptions(options);
        }
        for (ExamPaperLib question : checkboxQuestions) {
            ExamOption option=new ExamOption();
            option.setLibId(question.getLibId());
            List<ExamOption> options = examOptionService.selectExamOptionList(option);
            question.setOptions(options);
        }
        for (ExamPaperLib question : indefiniteQuestions) {
            ExamOption option=new ExamOption();
            option.setLibId(question.getLibId());
            List<ExamOption> options = examOptionService.selectExamOptionList(option);
            question.setOptions(options);
        }

        mmap.put("radioQuestions", radioQuestions);
        mmap.put("checkboxQuestions", checkboxQuestions);
        mmap.put("indefiniteQuestions", indefiniteQuestions);
        mmap.put("subjectiveQuestions", subjectiveQuestions);

        return prefix + "/preview";
    }

    /**
     * 保存学生答题
     */
    @Log(title = "保存学生答题", businessType = BusinessType.INSERT)
    @PostMapping("/submit")
    @ResponseBody
    public AjaxResult submit(@RequestBody Map<String, Object> params)
    {
        String paperId = (String) params.get("paperId");
        Integer userId = Integer.parseInt(params.get("userId").toString());
        @SuppressWarnings("unchecked")
        Map<String, String> answers = (Map<String, String>) params.get("answers");
        SysStudent sysStudent=new SysStudent();
        sysStudent.setUserId(userId+"");
        SysStudent ss=studentService.selectSysStudentList(sysStudent).stream().findFirst().get();
        String studenId=null;
        if(ss!=null){
            studenId=ss.getStudentId();
        }
        Long duration = Long.valueOf(params.get("duration").toString());

        if (paperId == null || userId == null || answers == null || duration == null) {
            return AjaxResult.error("参数不完整");
        }

        try {
            StudentScore studentScore = examPaperService.saveStudentAnswers(paperId, userId+"", studenId, answers, duration);
            return AjaxResult.success(studentScore);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 答题页面
     */
    @RequiresPermissions("jxsx:paper:view")
    @GetMapping("/exam/{paperId}")
    public String exam(@PathVariable("paperId") String paperId, ModelMap mmap)
    {
        // 获取试卷信息
        ExamPaper examPaper = examPaperService.selectExamPaperByPaperId(paperId);
        mmap.put("examPaper", examPaper);

    Date startTime = examPaper.getStartTime();
    Date endTime = examPaper.getEndTime();
     //获取两个年月日时分秒的分钟差
       long minutes = (endTime.getTime() - startTime.getTime()) / 60000;
        // 将Duration转换为分钟
       long durationInMinutes = examPaper.calculateDurationInMinutes();

        mmap.put("duration", minutes);
        // 获取各类题型试题
        List<ExamPaperLib> radioQuestions = examPaperService.selectExamPaperLibByType(paperId, "0");
        List<ExamPaperLib> checkboxQuestions = examPaperService.selectExamPaperLibByType(paperId, "1");
        List<ExamPaperLib> indefiniteQuestions = examPaperService.selectExamPaperLibByType(paperId, "2");
        List<ExamPaperLib> subjectiveQuestions = examPaperService.selectExamPaperLibByType(paperId, "3");
        
        // 获取每道题的选项
        for (ExamPaperLib question : radioQuestions) {
            ExamOption option=new ExamOption();
            option.setLibId(question.getLibId());
            List<ExamOption> options = examOptionService.selectExamOptionList(option);
            question.setOptions(options);
        }
        for (ExamPaperLib question : checkboxQuestions) {
            ExamOption option=new ExamOption();
            option.setLibId(question.getLibId());
            List<ExamOption> options = examOptionService.selectExamOptionList(option);
            question.setOptions(options);
        }
        for (ExamPaperLib question : indefiniteQuestions) {
            ExamOption option=new ExamOption();
            option.setLibId(question.getLibId());
            List<ExamOption> options = examOptionService.selectExamOptionList(option);
            question.setOptions(options);
        }
        
        mmap.put("radioQuestions", radioQuestions);
        mmap.put("checkboxQuestions", checkboxQuestions);
        mmap.put("indefiniteQuestions", indefiniteQuestions);
        mmap.put("subjectiveQuestions", subjectiveQuestions);
        
        // 获取当前用户信息
        SysUser user = ShiroUtils.getSysUser();
        mmap.put("userId", user.getUserId());
        return prefix + "/exam";
    }

    /**
     * 查询试卷答题详情
     */
    @GetMapping("/detail/{paperId}")
    public String detail(@PathVariable("paperId") String paperId, ModelMap mmap) {
        // 获取当前登录用户ID
        String userId = ShiroUtils.getSysUser().getUserId()+"";
        SysStudent sysStudent1=new SysStudent();
        sysStudent1.setUserId(userId);
        List<SysStudent> sysStudentList=studentService.selectSysStudentList(sysStudent1);
        SysStudent sysStudent= sysStudentList.get(0);
        String studentId =sysStudent.getStudentId();
        // 获取试卷答题详情
        Map<String, Object> detail = examPaperService.selectPaperAnswerDetail(paperId, studentId,userId);
        mmap.put("paper", detail.get("paper"));
        mmap.put("score", detail.get("score"));
        mmap.put("questions", detail.get("questions"));
        return prefix + "/paperDetail";
    }

    /**
     * 查询试卷列表（学生）
     */
    @GetMapping("/list")
    public String list(ExamPaper examPaper, ModelMap mmap) {
        // 获取当前登录用户ID
//        String userId = SecurityUtils.getUserId();
//        String studentId = SecurityUtils.getLoginUser().getUser().getStudentId();
//
//        // 获取所有试卷
//        List<ExamPaper> allPapers = examPaperService.selectExamPaperList(examPaper);
//        // 获取已答题试卷
//        List<ExamPaper> answeredPapers = examPaperService.selectAnsweredPaperList(studentId);
//
//        // 设置已答题试卷的状态为11（已完成）
//        for (ExamPaper paper : allPapers) {
//            for (ExamPaper answeredPaper : answeredPapers) {
//                if (paper.getPaperId().equals(answeredPaper.getPaperId())) {
//                    paper.setStatus("11");
//                    break;
//                }
//            }
//        }
//
//        mmap.put("list", allPapers);
        return "jxsx/paper/paperList";
    }

//    /**
//     * 获取试卷报告
//     */
//    @GetMapping("/report/{paperId}")
//    @ResponseBody
//    public AjaxResult getPaperReport(@PathVariable("paperId") String paperId) {
//        Map<String, Object> report = examPaperService.getPaperReport(paperId);
//        return AjaxResult.success(report);
//    }

    /**
     * 显示试卷报告页面
     */
    @GetMapping("/report/{paperId}")
    public String reportPage(@PathVariable("paperId") String paperId, ModelMap mmap) {
        Map<String, Object> report = examPaperService.getPaperReport(paperId);
        mmap.putAll(report);
        return prefix + "/report";
    }

}
